'use strict';

const uidObj = require('uni-id');
// const uidPay = require('uni-pay');
const {
	XMLParser
} = require("fast-xml-parser");

const db = uniCloud.database();
const {
	mainSpaceId
} = require('config-main-space')
exports.main = async (event, context) => {
	let response = {
		mpserverscssComposedResponse: true,
		statusCode: 200,
		headers: {
			'content-type': 'text/xml;charset=utf-8'
		},
		body: `<xml><return_code><![CDATA[FAILD]]></return_code><return_msg><![CDATA[异常回调]]></return_msg></xml>`
	};

	let data = event.body
	if (event.isBase64Encoded) {
		data = new Buffer(data, 'base64').toString();
	}
	console.log(data)
	const path = event.path;
	// 错误记录
	const errorObj = {
		msg: ''
	};

	let res = {};
	let notifyType = 'payment';
	let payObj = {
		name: '微信支付',
		way: 'wxpay'
	};
	switch (path) {
		case '/':
		case '/wxpay':
		case '/wxpay-app':
		case '/wxpay-h5wx':
			const parser = new XMLParser();
			res = parser.parse(data);
			res = res.xml
			try {
				//特殊处理transaction_id
				let transaction_ids = data.split('<transaction_id><![CDATA[')
				if (transaction_ids.length > 0) {
					let transaction_id = transaction_ids[1].split("]]></transaction_id>")[0]
					res.transaction_id = transaction_id
				}
			} catch (e) {

			}

			break;
		case '/alipay':
		case '/alipay-app':
			var queryArr = data.split("&");
			queryArr.forEach(function(item) {
				var key = item.split("=")[0];
				var value = item.split("=")[1];
				res[key] = value;
			});
			res.total_fee = res.total_amount * 100
			res.transaction_id = res.trade_no
			payObj.name = '支付宝支付';
			payObj.way = 'alipay';
			break;
		default:
			break;
	}

	// 根据商户订单号,判断支付金额是否一致
	// 根据商户订单号 
	// 	1.修改订单状态为 待发货
	// 	2.修改订单支付数据
	// 	3.分销订单写入分销商数据
	// 根据订单获取下单人
	// 根据下单人累计消费金额
	// 根据订单设置,如果为支付成功后扣减库存,则扣减对应商品扣除
	// 修改订单支付数据
	// 写入订单日志
	if (res && (res.return_code == 'SUCCESS' || res.result_code == 'SUCCESS' || res.trade_status ==
			'TRADE_SUCCESS') && notifyType == 'payment') {
		let outTradeNo = res.out_trade_no
		let totalFee = res.total_fee
		let transactionId = res.transaction_id
		let openid = res.openid

		// 系统订单号
		const [order_id] = outTradeNo.split('_');

		let orderRes = await db.collection('wmzmall-order')
			.where({
				is_delete: 0,
				order_id: order_id
			})
			.limit(1)
			.get();

		const [order] = orderRes.data;
		if (!(order && order._id)) {
			errorObj.msg = `订单[${outTradeNo}]不存在`;
		}
		/* else if (order.order_actural_paid != totalFee) {
			errorObj.msg = `订单[${outTradeNo}]支付金额不一致，[${order.order_actural_paid}] != [${totalFee}]`;
		} */

		if (errorObj.msg) {
			uniCloud.logger.info(errorObj.msg);
			// 记录error日志

			return response;
		}

		// 订单详情
		const orderDetailRes = await db.collection('wmzmall-order-detail').where({
			order_id: order.order_id
		}).get();
		if (!(orderDetailRes.data && orderDetailRes.data.length)) {
			errorObj.msg = `订单[${outTradeNo}]的商品不存在`;
		}

		if (errorObj.msg) {
			uniCloud.logger.info(errorObj.msg);
			// 记录error日志

			return response;
		}

		// 已省金额
		let member_economize = 0;
		orderDetailRes.data.forEach(x => {
			// 会员已省金额
			member_economize += x.economize_amount;
		});

		const uid = order.create_uid;
		const uname = order.order_member_name;
		// 当前时间
		const nowdate = Date.now();

		// 拼团订单
		// 判断是否已成团
		// 	未成团
		// 		1. 修改参团表（参团中、几人团、团有效期、团成员）
		// 		2. 修改订单表（待成团）
		// 	已成团
		//		1. 修改参团表（参团中、几人团、团有效期、团成员)
		//		2. 修改订单表（待发货）
		// 拼团表（参团人、参团人数、参团订单数）

		let groupData = {};
		let groupChiefData = {};
		let groupMemberIdx = 0
		if (order.group_id) {
			try {
				// false 不验证活动是否已结束或已过期
				groupData = await getGroup(order.group_id, false);

				if (order.group_chief_id) {
					// 获取参团数据
					groupChiefData = await getGroupChief(order.group_chief_id, false);
				} else {
					// 获取订单团购数据
					groupChiefData = await getGroupChiefByOrder(order.order_id, false);
				}

				if (groupChiefData.state == '已取消') {
					errorObj.msg = `当前拼单活动已取消`;
				}

				groupMemberIdx = groupChiefData.group_members.findIndex(x => x.order_id == order.order_id);
				if (groupMemberIdx == -1) {
					errorObj.msg = `当前订单未参团`;
				}
			} catch (e) {
				errorObj.msg = e;
			}
		}

		// 订单配置
		const orderConfig = await getOrderConfig(order.shop_id);

		const ip = event.headers['x-real-ip'];

		// 开启事务
		const dbtran = await db.startTransaction();
		try {
			// 分销订单
			if (order.is_fxs == '是') {
				if (order.order_fxs_uid && order.order_fxs_amount) {
					// 上级
					await dbtran.collection('wmzmall-distributor').doc(order.order_fxs_uid).update({
						fxs_unsettled_amount: db.command.inc(order.order_fxs_amount),
						fxs_order_cnt: db.command.inc(1),
						version: db.command.inc(1),

						last_modify_uid: payObj.way,
						last_modify_time: nowdate
					});

					await dbtran.collection('wmzmall-distributor-record').add({
						fxs_uid: order.order_fxs_uid,
						profit_amount: order.order_fxs_amount,
						member_guid: uid,
						member_openid: order.order_member_openid,
						member_name: order.order_member_name,
						member_headimg: order.order_member_headimg,
						order_id: order.order_id,
						source_desc: `下级成员购买[${order.order_info} * ${order.order_goods_cnt}]`,
						source_type: '下单',
						remark: '',
						state: '未结算',
						version: 1,
						is_delete: 0,
						create_uid: uid,
						create_time: nowdate
					});
					await dbtran.collection('wmzmall-distributor-log').add({
						fxs_uid: order.order_fxs_uid,
						oper_content: `下级会员下单[+${order.order_fxs_amount / 100}]`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下级会员`,
						version: 1,
						is_delete: 0,
						create_uid: uid,
						create_time: nowdate
					});
				}

				if (order.order_fxs_uid2 && order.order_fxs_amount2) {
					// 上上级
					await dbtran.collection('wmzmall-distributor').doc(order.order_fxs_uid2).update({
						fxs_unsettled_amount: db.command.inc(order.order_fxs_amount2),
						fxs_order_cnt: db.command.inc(1),
						version: db.command.inc(1),

						last_modify_uid: payObj.way,
						last_modify_time: nowdate
					});

					await dbtran.collection('wmzmall-distributor-record').add({
						fxs_uid: order.order_fxs_uid2,
						profit_amount: order.order_fxs_amount2,
						member_guid: uid,
						member_openid: order.order_member_openid,
						member_name: order.order_member_name,
						member_headimg: order.order_member_headimg,
						order_id: order.order_id,
						source_desc: `下下级成员购买[${order.order_info} * ${order.order_goods_cnt}]`,
						source_type: '下单',
						remark: '',
						state: '未结算',
						version: 1,
						is_delete: 0,
						create_uid: uid,
						create_time: nowdate
					});
					await dbtran.collection('wmzmall-distributor-log').add({
						fxs_uid: order.order_fxs_uid2,
						oper_content: `下下级会员下单[+${order.order_fxs_amount2 / 100}]`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下下级会员`,
						version: 1,
						is_delete: 0,
						create_uid: uid,
						create_time: nowdate
					});
				}

				// 记录下单人 分销数据、累计消费、已省金额
				const memberRes = await dbtran.collection('wmzmall-member').doc(uid).update({
					member_monetary: db.command.inc(totalFee),
					myfxs_order_cnt: db.command.inc(1),

					myfxs_profit_amount: db.command.inc(order.order_fxs_amount),
					myfxs_profit_amount2: db.command.inc(order.order_fxs_amount2),

					member_economize: db.command.inc(member_economize)
				});
			} else {
				// 修改下单人 累计消费、已省金额
				const memberRes = await dbtran.collection('wmzmall-member').doc(uid).update({
					member_monetary: db.command.inc(totalFee),

					member_economize: db.command.inc(member_economize)
				});
			}

			const orderUpdateObj = {
				state: '待发货'
			}
			const groupUpdateObj = {};
			const groupMemberUpdateObj = {};

			// 拼团订单
			// 判断是否已成团
			// 	待成团
			// 		1. 修改参团表（状态、已付款数）
			// 		2. 修改订单表（待成团）
			// 	已成团
			//		1. 修改参团表（状态、已付款数)
			//		2. 修改订单表（待发货）
			// 拼团表（参团人、参团人数、参团订单数）

			// 拼团订单
			if (groupData && groupData._id) {
				// 参团人
				const groupMember = {
					order_id: order.order_id,
					uid: order.create_uid,
					// uname: order.order_member_name,
					uname: '',
					uheadimg: order.order_member_headimg,
					pay_time: nowdate,
					state: '已付款'
				};
				// 已参团人数大于等于团购数量
				if (groupChiefData.group_member_pay_cnt >= groupData.group_num - 1) {
					// 成团时间
					orderUpdateObj.order_group_time = nowdate;
					// 已成团
					orderUpdateObj.state = '待发货';
					groupMemberUpdateObj.state = '已成团';

					// 成团数
					groupUpdateObj.group_success_num = db.command.inc(1);
				} else {
					// 待成团
					orderUpdateObj.state = '待成团';
					groupMemberUpdateObj.state = '参团中';
				}

				if (!order.group_chief_id) {
					// 开团订单有效期
					orderUpdateObj.order_expire_time = Date.now() + groupData.group_time * 60 * 60 * 1000;
					// 修改到期时间
					groupMemberUpdateObj.expire_time = orderUpdateObj.order_expire_time;
				} else {
					// 参团订单有效期
					orderUpdateObj.order_expire_time = groupChiefData.expire_time;
				}

				// 修改参团表（状态、已付款数)
				await dbtran.collection('wmzmall-market-groupbuy-member').doc(groupChiefData._id).update({
					['group_members.' + groupMemberIdx]: {
						state: '已付款'
					},
					group_member_pay_cnt: db.command.inc(1),
					...groupMemberUpdateObj
				});

				// 插入最新的参团人
				groupData.group_members.unshift(groupMember);

				// 拼团表（参团人、参团人数、参团订单数）
				await dbtran.collection('wmzmall-market-groupbuy').doc(groupData._id).update({
					group_member_cnt: db.command.inc(1),
					group_order_cnt: db.command.inc(1),
					group_members: groupData.group_members.slice(0, 6),

					version: db.command.inc(1),

					last_modify_uid: uid,
					last_modify_time: nowdate,
					last_modify_uname: payObj.name,

					...groupUpdateObj
				});
			}

			// 支付后扣减库存
			if (orderConfig.stock_ded_type == 2) {
				// 扣减库存
				orderUpdateObj.order_ded_stock = 1;
			}

			// 更改订单状态
			await dbtran.collection('wmzmall-order').doc(order._id).update({
				last_modify_time: nowdate,
				last_modify_uid: payObj.way,
				last_modify_uname: payObj.name,

				// 交易单号
				out_trade_no: outTradeNo,

				version: db.command.inc(1),
				order_pay_state: '已付款',
				order_pay_no: transactionId,
				order_pay_way: payObj.name,
				// 支付时间
				order_pay_time: nowdate,

				...orderUpdateObj
			});

			// 订单日志
			await dbtran.collection('wmzmall-order-log').add({
				order_id: order.order_id,
				log_type: '订单支付',
				current_state: orderUpdateObj.state,
				prev_state: '待付款',
				ip: ip,
				is_delete: 0,
				create_uid: uid,
				create_uname: uname,
				create_time: nowdate
			});


			// 提交事务
			await dbtran.commit();

			// 修改订单支付数据
			await db.collection('wmzmall-order-pay').where({
				order_id: order.order_id
			}).update({
				version: db.command.inc(1),
				pay_state: '已付款',
				pay_notify: event,
				pay_money: totalFee,
				pay_time: nowdate,
				pay_no: transactionId,
				pay_openid: openid
			});

			// 已成团订单
			if (groupMemberUpdateObj.state == '已成团') {
				const order_ids = [];
				const order_logs = [];
				// 修改对应参团人员订单状态为待发货
				for (let i = 0; i < groupChiefData.group_members.length; i++) {
					// 跳过当前支付的参团人员
					if (i == groupMemberIdx) continue;

					let groupMember = groupChiefData.group_members[i]

					order_ids.push(groupMember.order_id);
					order_logs.push({
						order_id: groupMember.order_id,
						log_type: '拼单成功',
						current_state: '待发货',
						prev_state: '待成团',
						ip: ip,
						is_delete: 0,
						create_uid: uid,
						create_time: nowdate
					})
				}

				// 订单日志
				if (order_logs.length) await db.collection('wmzmall-order-log').add(order_logs);

				// 更改订单状态
				await db.collection('wmzmall-order').where({
					order_id: db.command.in(order_ids),
					state: '待成团'
				}).update({
					order_group_time: nowdate,

					last_modify_time: nowdate,
					last_modify_uid: uid,
					last_modify_uname: payObj.name,

					version: db.command.inc(1),

					state: '待发货'
				});
			}

			// 支付后扣减库存
			if (orderConfig.stock_ded_type == 2) {
				for (let i = 0; i < orderDetailRes.data.length; i++) {
					let x = orderDetailRes.data[i];
					// 扣减库存
					await db.collection('wmzmall-goods')
						.where({
							_id: x.goods_id,
							stock_num: db.command.gte(x.goods_num)
						})
						.update({
							stock_num: db.command.inc(-x.goods_num),
							sale_cnt: db.command.inc(x.goods_num)
						});

					// 扣减SKU库存
					if (x.goods_sku) {
						await db.collection('wmzmall-goods-sku')
							.where({
								goods_id: x.goods_id,
								goods_sku: x.goods_sku,
								stock_num: db.command.gte(x.goods_num)
							})
							.update({
								stock_num: db.command.inc(-x.goods_num),
								sale_cnt: db.command.inc(x.goods_num)
							});
					}
				}
			}
			let title = '收款';
			let cate = '商城订单';
			let type = 0;
			let appId = order.app_id;
			let shopId = order.shop_id;
			let orderNo = transactionId;
			let way = order.order_pay_way;
			let payMoney = order.order_total_money;

			if (way.indexOf('支付宝') > -1) {
				way = '支付宝支付';
			}
			let shopie = {
				app_id: appId,
				shop_id: shopId,
				order_no: orderNo,
				title: title,
				cate: cate,
				type: type,
				way: way,
				money: payMoney,
				creator_id: order.creator_id,
				creator_name: order.creator_name,
				create_time: new Date().getTime() 
			};
			let addShopieResult = await db.collection('wmzmall-shopie').add(shopie);
			let tdb = uniCloud.database({
				provider: 'tencent',
				spaceId: mainSpaceId
			})
			await tdb.collection('wmzmall-shopie').add(shopie)
			if (payObj.way == 'wxpay') {
				response.body =
					`<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
			} else if (payObj.way = 'alipay') {
				response.headers['content-type'] = 'text/plain';
				response.body = 'success';
			}
		} catch (e) {
			// 回滚事务
			await dbtran.rollback();
			errorObj.msg = e.message;
		}

		if (errorObj.msg) {
			// 记录异常支付回调数据
			await db.collection('wmzmall-logs').add(errorObj);
		}
	}

	if (notifyType == 'refund') {
		if (payObj.way = 'alipay') {
			response.headers['content-type'] = 'text/plain';
			response.body = 'success';
		}
	}

	return response;
};

/**
 * 订单配置
 */
async function getOrderConfig(shop_id) {
	const configRes = await db.collection('wmzmall-order-parameter').where({
		shop_id: shop_id
	}).get();

	const [orderConfig = {}] = configRes.data;

	return orderConfig;
}

/**
 * 根据拼团活动ID获取数据
 * verify 验证活动是否有效
 */
async function getGroup(id, verify = true) {
	const groupRes = await db.collection('wmzmall-market-groupbuy').doc(id).field({
		goods_id: true,
		goods_obj: true,
		goods_price: true,
		group_num: true,
		group_members: true,
		group_begin_time: true,
		group_end_time: true,
		group_time: true,
		state: true,
		is_delete: true
	}).get();

	const [group] = groupRes.data;
	if (!(group && group._id)) throw new Error(`拼团活动不存在`);

	// 验证活动是否有效
	if (verify) {
		const nowdate = Date.now();
		if (!(group.is_delete == 0 && group.state == '启用')) throw new Error(`拼团活动已停止`);
		if (!(group.group_begin_time <= nowdate && group.group_end_time >= nowdate)) throw new Error(`拼团活动已结束`);

		// 活动到期时间
		group.expires_time = (group.group_end_time - nowdate) / 1000;
	}

	return group;
}

/**
 * 根据拼团活动团长ID获取数据
 * verify 验证是否过期
 */
async function getGroupChief(id, verify = true) {
	const groupRes = await db.collection('wmzmall-market-groupbuy-member').doc(id).get();

	const [group] = groupRes.data;
	if (!(group && group._id)) throw new Error(`当前拼单不存在`);

	if (group.is_delete == 1) throw new Error(`当前拼单已停止`);
	if (verify) {
		if (group.state == '已取消') throw new Error(`当前拼单活动已取消`);
		if (group.expire_time && Date.now() > group.expire_time) throw new Error(`拼单活动已结束`);
	}

	return group;
}

/**
 * 根据拼团活动订单ID获取数据
 * verify 验证是否过期
 */
async function getGroupChiefByOrder(id, verify = true) {
	const groupRes = await db.collection('wmzmall-market-groupbuy-member').where({
		order_id: id
	}).limit(1).get();

	const [group] = groupRes.data;
	if (!(group && group._id)) throw new Error(`您的开团不存在`);

	if (group.is_delete == 1) throw new Error(`您的开团已停止`);
	if (verify) {
		if (group.state == '已取消') throw new Error(`您的开团已取消`);
		if (group.expire_time && Date.now() > group.expire_time) throw new Error(`拼单活动已结束`);
	}

	return group;
}



/**
 * 将 UTC+0 转换为 UTC+8
 */
function toDateUTC8(date) {
	// 小时 UTC+0 转换为 UTC+8
	date.setHours(date.getHours() + 8);
	return date;
}